﻿using serial_socket_wpf.ViewModule;
using System.IO.Ports;
using System.Windows;
using System.Net.Sockets;
using System.Net;


namespace serial_socket_wpf
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Serial_view_module _serial_in;
        private Serial_view_module _serial_out;
        private TcpServer_view_module _socket_out;

        private string[] _serials = null;
        public MainWindow()
        {
            InitializeComponent();

            _serials = SerialPort.GetPortNames();

            _serial_in = new Serial_view_module
            {
                baudrate = "921600",
                label = "serial_in",
            };
            _serial_out = new Serial_view_module
            {
                baudrate = "921600",
                label = "serial_out",
            };
            _socket_out = new TcpServer_view_module
            {
                btn_string = "start",
                label = "idle",
                local_ip = "127.0.0.1",
                port = "9595",
            };

            this.GridSerialOut.DataContext = _serial_out;
            this.GridSerialIn.DataContext = _serial_in;
            this.GridSocketOut.DataContext = _socket_out;

            _serial_in.serial.DataReceived += OnSerialInDataRecevied;
            _socket_out.DataReceived += OnSocketRecieve;
        }

        private void OnSerialInDataRecevied(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] buffer = new byte[2048];
            int len = _serial_in.serial.Read(buffer, 0, 2048);
            if (_serial_out.serial.IsOpen)
            {
                _serial_out.serial.Write(buffer, 0, len);
            }
            if (_socket_out.socket_writer != null)
            {
                _socket_out.socket_writer.Write(buffer, 0, len);
            }
        }

        private void OnSocketRecieve(byte[] src,int len)
        {
            if (_serial_in.serial.IsOpen)
            {
                _serial_in.serial.Write(src, 0, len);
            }
        }

    }
}
